<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge,chrome=1">
    <meta name="referrer" content="never">
    <title>导航</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        ul {
            list-style: none;
        }

        nav {
            position: fixed;
            top: 100px;
            left: 60px;
            overflow: hidden;
            border: 2px solid #333;
            z-index: 999;
        }

        nav div {
            float: left;
            width: 100px;
            height: 40px;
        }

        .red {
            /* rgb()  hsl() #16进制 */
            background-color: #f00; 
        }

        .green {
            background-color: #0f0;
        }

        .blue {
            background-color: #00f;
        }

        .container {
            width: 1200px;
            margin: 20px auto;
        }

        .container div {
            height: 2000px;
            margin-top: 50px;
            opacity: .4;
        }
    </style>
</head>
<body>
    <nav>
        <div class="red"></div>
        <div class="green"></div>
        <div class="blue"></div>
    </nav>
    <div class="container">
        <div class="red">first</div>
        <div class="green">second</div>
        <div class="blue">third</div>
    </div>

    <script type="text/javascript">
        // 点击导航条元素，找到内容对应元素与页面的上边距，赋予页面滚动上边距

        var navEle = document.querySelector("nav");

        // 事件委托
        navEle.onclick = function (){
            // 判断被点击元素是否是 欲添加事件的子元素
            var ele = event.target;
            if(ele.tagName == "DIV"){
                // 找到container对应元素距离页面的上边距
                var top = document.querySelector(".container ."+ele.className).offsetTop;
                
                // console.log(top);
                window.scroll({
                    top: top,
                    behavior: "smooth"
                })
            }
        }
    </script>
</body>
</html>